<template>
	<u-navbar :is-back="false" :is-fixed="true" :background="{background:'#ffffff'}" :border-bottom="false">
		<view style="width: 100%;">
			<u-tabs :list="tabsList" active-color="#117B12" :is-scroll="false" v-model="tabsCurrent"
				@change="tabsChange"></u-tabs>
		</view>
	</u-navbar>
	<u-sticky bg-color="#f9f9f9" z-index="999">
		<view class=" u-flex" style="background-color: #f9f9f9;">
			<view class="u-flex-1 u-content-color u-p-l-28">
				购物车({{list.length}})
			</view>
			<view class="u-p-28" @click="delCart">
				<u-icon name="trash" color="#999999" size="32"></u-icon>
			</view>
		</view>
	</u-sticky>
	<view class="u-p-l-28 u-p-r-28">
		<u-checkbox-group @change="checkboxGroupChange" :wrap="true" shape="circle" :size="34" :icon-size="20"
			style="display: block;">
			<view v-for="(item,index) in list" :key="item.sid" style="width: 100%;">
				<view class="box-radius u-flex bgw">
					<view class="u-flex u-p-20" style="width: 80upx;">
						<u-checkbox @change="checkboxChange" v-model="item.checked" :key="index" :name="item.sid"
							active-color="#117B12"></u-checkbox>
					</view>
					<view class="u-p-r-28 u-flex-1">
						<item :border="false" :detail="item" type="cart">
							<template v-slot:right>
								<view class="" v-if="tabsCurrent == 0">
									x{{item.count}}
								</view>
								<template v-if="tabsCurrent == 1">
									<view @click.stop="">
										<u-number-box :index="index" v-model="item.count" :step="1" :min="1" @blur="numberChange" @minus="numberChange" @plus="numberChange"></u-number-box>
									</view>
									
								</template>
							</template>
						</item>
					</view>
				</view>
				<u-gap height="28"></u-gap>
			</view>
		</u-checkbox-group>
	</view>
	<g-loadmore :status="loadmoreStatus" nodata-img="/static/images/nodata-cart.png" nodata-text="">
		<template #nodata>
			<view class="u-text-center">
				<text class="u-tips-color">你的购物车空空如也，</text>
				<text class="color-primary" @click="toMall">去逛逛~</text>
			</view>
		</template>
	</g-loadmore>
	<u-gap height="150"></u-gap>
	<view class="fixed-bottom bgw u-border-bottom" v-if="list.length>0">
		<u-checkbox-group :wrap="true" shape="circle" style="display: flex;">
			<view class="u-flex u-p-t-10 u-p-b-10 u-p-l-28 u-p-r-28" style="width: 100%;">
				<view class="">
					<u-checkbox @change="checkboxAllChange" v-model="allFlag" name="allFlag" shape="circle"
						active-color="#117B12">{{allFlag?'取消':'全选'}}</u-checkbox>
				</view>
				<view class="u-flex-1"></view>
				<view class="u-m-r-28">
					<text>已选{{checkedSids.length}}件，合计：</text>
					<text style="font-weight: bold;">￥</text>
					<text style="font-weight: bold;" class="u-font-40">{{totalPrice}}</text>
				</view>
				<u-button @click="submit" :custom-style="customStyle" type="primary" shape="circle">结 算</u-button>

			</view>
		</u-checkbox-group>
	</view>
</template>
<script setup>
	import store from '@/store/index.js';
	import mixins from '@/common/js/mixins.js';
	import mixinList from './js/mixinList.js';
	import {
		ref,
		reactive,
		computed,
		watch,
		getCurrentInstance
	} from 'vue'
	import {
		onReady,
		onLoad,
		onShow,
		onPageScroll
	} from '@dcloudio/uni-app'
	const {
		proxy,
	} = getCurrentInstance()
	const {
		nav,
		navLogin,
		modal
	} = proxy.$util;
	const {
		total,
		current_page,
		page_size,
		last_page,
		apiPath,
		loading,
		list,
		searchParams,
		getList,
		getNextList,
		loadmoreStatus,
		searchClear,
		searchConfirm,
		sortFieldName,
		oldCount
	} = mixinList();
	apiPath.value = 'getCart'
	const tabsCurrent = ref(0)
	const tabsList = [{
			id: 0,
			name: '报单区'
		},
		{
			id: 1,
			name: '消费商城'
		}
	];
	const customStyle = {
		height: '88rpx',
		lineHeight: '88rpx'
	}

	searchParams.type = computed(() => {
		return tabsList[tabsCurrent.value].id
	});
	sortFieldName.value = ''
	watch(tabsCurrent, async (val) => {
		await getList(1)
	})
	const tabsChange = (index) => {}

	const toMall = () => {
		if(tabsCurrent.value == 0){
			nav('/pages/list/list')
		}
		if(tabsCurrent.value == 1){
			nav('/pages/mall/mall')
		}
	}
	const checkedSids = computed(() => {
		let arr = list.filter(v => !!v.checked);
		return arr.map(v => v.sid)
	})
	const totalPrice = computed(() => {
		let arr = list.filter(v => !!v.checked);
		let nums = arr.map(v => v.price * v.count);
		let sum = eval(nums.join('+')) || 0
		return sum
	})
	const productList = computed(() => {
		let arr = list.filter(v => !!v.checked);
		return arr.map(v => {
			return {
				count: v.count,
				productSid: v.productSid
			}
		})
	})
	watch(() => checkedSids.value, (v) => {
		if (v.length == list.length && list.length != 0) {
			allFlag.value = true;
		} else {
			allFlag.value = false;
		}
	})
	const checkboxChange = () => {
		// console.log(checkedSids.value);
	}
	const checkboxGroupChange = (index) => {}
	const submit = async () => {
		if (checkedSids.value.length == 0) {
			uni.$u.toast('请选择商品');
			return
		}
		if (checkedSids.value.length != 1 && searchParams.type === 0) {
			uni.$u.toast('报单区只能结算一个商品！');
			return
		}
		uni.showLoading({
			title: '创建订单',
			mask: true
		});
		let orderData = {
			shoppingCartSid: checkedSids.value,
			// price:totalPrice.value,
			productList: productList.value,
			pickup:1
		};
		try {
			let defaultAddress = await proxy.$u.api.getDefaultAddress();
			if (defaultAddress.data) {
				orderData.addressSid = defaultAddress.data.sid
			}
		} catch (e) {
			uni.$u.toast('错误');
		}
		proxy.$u.api.addOrder(orderData).then(res => {
			let {
				code,
				msg,
				data
			} = res;
			if (code == 200) {
				// console.log(data);
				// 24-7295a9ca6ebe4fd68da4c44429fce4fb
				navLogin('/pagesSub/editOrder/editOrder?sid=' + data)
			} else {
				uni.$u.toast(msg || '错误');
			}
		})
	}
	const allFlag = ref(false)
	const checkboxAllChange = (e) => {
		list.forEach(v => {
			v.checked = e.value
		})
	}
	const numberChange = (d) =>{		
		let { value,index }=d;
		let sid = list[index].sid;
		let count = value;
		if(count === 0){
			return;
		}
		if(oldCount[sid] === count){
			return;
		}
		uni.showLoading({
			title: '加载中',
			mask: true
		});
		proxy.$u.api.updataCart({
			count,sid
		}).then(res => {
			let {
				code,
				msg,
				data
			} = res;
			if (code == 200) {
				oldCount[sid] = count;
				// uni.$u.toast(msg || '成功');	
			} else {
				uni.$u.toast(msg || '购物车更新失败');
				getList(1)
			}
		}).catch(res=>{
			getList(1)
		})
		
	}
	const delCart = () => {
		if (checkedSids.value.length == 0) {
			uni.$u.toast('请选择商品');
			return
		}
		modal('请确定是否删除该商品？').then(() => {
			uni.showLoading({
				title: '加载中',
				mask: true
			});
			proxy.$u.api.deleteCart({
				sidList: checkedSids.value
			}).then(res => {
				let {
					code,
					msg,
					data
				} = res;
				if (code == 200) {
					uni.$u.toast(msg || '成功');
					getList(1)
				} else {
					uni.$u.toast(msg || '错误');
				}
			})
		}).catch(() => {

		})

	}
	onReady(() => {

	})
	onLoad(async (d) => {

	})
	onShow(async () => {
		await getList(1)
	})
	onPageScroll(e => {

	})
</script>
<style>

</style>
<style lang="scss" scoped>
	.fixed-bottom {
		background-color: #ffffff;
		box-shadow: 0 -4upx 20upx 0 rgba(0, 0, 0, 0.06);
		bottom: 50px;
		z-index: 999;
	}
</style>